package com.bawei.lib_cache.lru

import com.baway.cache.ICache
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow

/**
 * 使用LRU算法来实现
 * 特点:LRU算法自我管理内存
 * 实现:使用LinkedHashMap
 */
object KVLruCache: ICache {
    private val initinalCapacity=32//初始容量带下
    private val loadFactor=0.85f//扩容因子
    private val accessPrder=true//true代表访问顺序,有操作就向链表前面插入

    //参考Glide内存缓存时间
    private val lruCache:MutableMap<String,Any> = LinkedHashMap<String,Any>(32,0.85f,true)//true代表访问顺序,有操作就向链表前面插入


    @Synchronized
    override fun putString(key: String, value: String) {
      lruCache.put(key,value)
    }

    @Synchronized
    override fun putInt(key: String, value: Int) {
        lruCache.put(key,value)
    }

    @Synchronized
    override fun putLong(key: String, value: Long) {
        lruCache.put(key,value)
    }

    @Synchronized
    override fun putBool(key: String, value: Boolean) {
        lruCache.put(key,value)
    }

    @Synchronized
    override fun getString(key: String): Flow<String> {
      return flow {
          lruCache.get(key).toString()
      }
    }

    @Synchronized
    override fun getInt(key: String): Flow<Int> {
        return flow {
            lruCache.get(key) as Int
        }
    }

    @Synchronized
    override fun getLong(key: String): Flow<Long> {
        return flow {
            lruCache.get(key) as Long
        }
    }
    @Synchronized
    override fun getBool(key: String): Flow<Boolean> {
        return flow {
            lruCache.get(key) as Boolean
        }
    }
}